;;; Lispy-Fennel (LF) --- The Functional Fennel Library
;;;
;;; Copyright (C) 2020 Kevin "The Nuclear" Bloom <nuclearkev@dragora.org>
;;;
;;; This file is part of LF.
;;;
;;; LF is free software: you can redistribute it and/or modify
;;; it under the terms of the MIT License.
;;;
;;; LF is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; MIT License for more details.
;;;
;;; You should have received a copy of the MIT License
;;; along with LF.  If not, see <https://opensource.org/licenses/MIT>.

(local str {})

(fn str.take [s ind]
    (string.sub s 1 ind))

(fn str.drop [s ind]
    (string.sub s ind))

(fn str.split [s by]
    (var current s)
    (var tbl-of-strings [])
    (var spliting? true)
    (while spliting?
      (var (start end) (string.find current by))
      (if start
        (do (table.insert tbl-of-strings (str.take current (- start 1)))
            (set current (str.drop current (+ end 1))))
        (do (table.insert tbl-of-strings current)
            (set spliting? false))))
    tbl-of-strings)

;; TODO: Work when FIR and LST are the same
(fn str.substring-between [s fir lst]
  "Returns a substring of S defined by 2 strings, FIR and LST.
   The benefit of this is that if there are other instances of LST before the
   instance you want, they won't get caught.
   I.e.: You wish to get the value of the second line of \"this \n is a \n test\",
   You would just use (string-between str \"is a\" \"\n\")"
  (if (and s fir lst)
    (let [fir-pos (string.find s fir)]
      (if fir-pos
        (let [up-to-fir (str.drop s fir-pos)
              lst-pos (string.find up-to-fir lst)]
          (if lst-pos
            (str.take up-to-fir lst-pos)))))))

str
